package hk.linkcredit.awardservice.award.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import hk.linkcredit.awardservice.award.mapper.AwardConfigMapper;
import hk.linkcredit.awardservice.award.domain.entity.AwardConfig;
import hk.linkcredit.awardservice.award.service.IAwardConfigService;
import hk.linkcredit.awardservice.award.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 奖励配置Service业务层处理
 *
 * @author african-loan
 * @date 2022-06-22
 */
@Service
public class AwardConfigServiceImpl extends ServiceImpl<AwardConfigMapper, AwardConfig> implements IAwardConfigService {

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询奖励配置
     *
     * @param id 奖励配置ID
     * @return 奖励配置
     */
    @Override
    public AwardConfig selectAwardConfigById(Long id) {
        return this.getById(id);
    }

    /**
     * 查询奖励配置列表
     *
     * @param awardConfig 奖励配置
     * @return 奖励配置
     */
    @Override
    public List<AwardConfig> selectAwardConfigList(AwardConfig awardConfig) {
        return this.list(new QueryWrapper<>(awardConfig).last("order by id desc"));
    }

    /**
     * 新增奖励配置
     *
     * @param awardConfig 奖励配置
     * @return 结果
     */
    @Override
    public int insertAwardConfig(AwardConfig awardConfig) {
        awardConfig.setCreateTime(new Date());
        return baseMapper.insert(awardConfig);
    }

    /**
     * 修改奖励配置
     *
     * @param awardConfig 奖励配置
     * @return 结果
     */
    @Override
    public int updateAwardConfig(AwardConfig awardConfig) {
        awardConfig.setUpdateTime(new Date());
        return baseMapper.updateById(awardConfig);
    }

    /**
     * 批量删除奖励配置
     *
     * @param ids 需要删除的奖励配置ID
     * @return 结果
     */
    @Override
    public int deleteAwardConfigByIds(Long[] ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除奖励配置信息
     *
     * @param id 奖励配置ID
     * @return 结果
     */
    @Override
    public int deleteAwardConfigById(Long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public List<AwardConfig> getAwardConfigs(Long actId) {
        List<AwardConfig> awardConfigs = baseMapper.getAwardConfigs(actId);
        //如果方式为比例，则 用配置金额
        String proportionalAmount = configService.selectConfigByKey("award-proportional-amount");
        awardConfigs.forEach(e -> {
            if ("1".equals(e.getAwardMethod())) { //如果是比例取配置的金额
                //分销比例
                e.setProportionalAmount(new BigDecimal(proportionalAmount));
            }
        });
        return awardConfigs;
    }

}
